/*
Copyright 2022.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controllers

import (
	"context"
	"github.com/go-logr/logr"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	networkv1 "k8s.io/api/networking/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
	"strings"

	myAppsv1 "mashibing.com/pkg/mashibing-deployment/api/v1"
)

// MsbDeploymentReconciler reconciles a MsbDeployment object
type MsbDeploymentReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

//+kubebuilder:rbac:groups=apps.mashibing.com,resources=msbdeployments,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=apps.mashibing.com,resources=msbdeployments/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=apps.mashibing.com,resources=msbdeployments/finalizers,verbs=update

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the MsbDeployment object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.13.0/pkg/reconcile
func (r *MsbDeploymentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	logger := log.FromContext(ctx, "MsbDeployment", req.NamespacedName)

	// 处理资源
	// 1. 获取资源对象
	md := new(myAppsv1.MsbDeployment)
	if err := r.Client.Get(ctx, req.NamespacedName, md); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}
	mdCopy := md.DeepCopy()
	// 获取deployment对象
	// 2.获取deployment对象
	deploy := new(appsv1.Deployment)
	if err := r.Client.Get(ctx, req.NamespacedName, deploy); err != nil {
		if errors.IsNotFound(err) {
			if createErr := r.createDeployment(ctx, mdCopy, logger); createErr != nil {
				return ctrl.Result{}, createErr
			}
		} else {
			logger.Error(err, "deployment")
			return ctrl.Result{}, err
		}
	} else {
		if updateErr := r.updateDeployment(ctx, mdCopy, logger); updateErr != nil {
			return ctrl.Result{}, updateErr
		}
	}
	// 处理service
	// 3. 获取service
	svc := new(corev1.Service)
	if err := r.Client.Get(ctx, req.NamespacedName, svc); err != nil {
		// service不存在
		if errors.IsNotFound(err) {
			if strings.ToLower(mdCopy.Spec.Expose.Mode) == "ingress" {
				if createErr := r.createService(ctx, mdCopy, logger); createErr != nil {
					return ctrl.Result{}, createErr
				}
			} else if strings.ToLower(mdCopy.Spec.Expose.Mode) == "nodeport" {
				if updateErr := r.createNodePortService(ctx, mdCopy, logger); updateErr != nil {
					return ctrl.Result{}, updateErr
				}
			}
		} else {
			logger.Error(err, "service")
			return ctrl.Result{}, err
		}
	} else {
		// service已存在
		if strings.ToLower(mdCopy.Spec.Expose.Mode) == "ingress" {
			if updateErr := r.updateService(ctx, mdCopy, logger); updateErr != nil {
				return ctrl.Result{}, updateErr
			}
		} else if strings.ToLower(mdCopy.Spec.Expose.Mode) == "nodeport" {
			if updateErr := r.updateNodePortService(ctx, mdCopy, logger); updateErr != nil {
				return ctrl.Result{}, updateErr
			}
		}

	}
	// 处理endpoint
	// 4.获取ingress
	ig := new(networkv1.Ingress)
	if err := r.Client.Get(ctx, req.NamespacedName, ig); err != nil {
		// ingress不存在
		if errors.IsNotFound(err) {
			if strings.ToLower(mdCopy.Spec.Expose.Mode) == "ingress" {
				r.createIngress(ctx, mdCopy, logger)
			} else if strings.ToLower(mdCopy.Spec.Expose.Mode) == "nodeport" {
				return ctrl.Result{}, err
			}
		}
	} else {
		// ingress已存在
		if strings.ToLower(mdCopy.Spec.Expose.Mode) == "ingress" {
			if updateErr := r.updateIngress(ctx, mdCopy, logger); updateErr != nil {
				return ctrl.Result{}, updateErr
			}
		} else if strings.ToLower(mdCopy.Spec.Expose.Mode) == "nodeport" {
			if deleteErr := r.deleteIngress(ctx, mdCopy, logger, ig); deleteErr != nil {
				return ctrl.Result{}, deleteErr
			}
		}

	}

	return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *MsbDeploymentReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&myAppsv1.MsbDeployment{}).
		Complete(r)
}

func (r *MsbDeploymentReconciler) createDeployment(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	deploy, err := NewDeployment(md)
	if err != nil {
		logger.Error(err, "create deployment")
		return err
	}

	err = r.Client.Create(ctx, deploy)
	if err != nil {
		logger.Error(err, "create deployment on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) updateDeployment(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	deploy, err := NewDeployment(md)
	if err != nil {
		logger.Error(err, "create deployment")
		return err
	}

	err = r.Client.Update(ctx, deploy)
	if err != nil {
		logger.Error(err, "update deployment on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) createService(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	svc, err := NewService(md)
	if err != nil {
		logger.Error(err, "create service")
		return err
	}

	err = r.Client.Create(ctx, svc)
	if err != nil {
		logger.Error(err, "create service on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) createNodePortService(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	svc, err := NewNodePortService(md)
	if err != nil {
		logger.Error(err, "create service")
		return err
	}

	err = r.Client.Create(ctx, svc)
	if err != nil {
		logger.Error(err, "create nodeport service on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) updateService(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	svc, err := NewService(md)
	if err != nil {
		logger.Error(err, "create service")
		return err
	}

	err = r.Client.Update(ctx, svc)
	if err != nil {
		logger.Error(err, "update service on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) updateNodePortService(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	svc, err := NewNodePortService(md)
	if err != nil {
		logger.Error(err, "create service")
		return err
	}

	err = r.Client.Update(ctx, svc)
	if err != nil {
		logger.Error(err, "update nodeport service on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) createIngress(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	ig, err := NewIngress(md)
	if err != nil {
		logger.Error(err, "create ingress")
		return err
	}

	err = r.Client.Create(ctx, ig)
	if err != nil {
		logger.Error(err, "create ingress on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) updateIngress(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger) error {
	ig, err := NewIngress(md)
	if err != nil {
		logger.Error(err, "create ingress")
		return err
	}

	err = r.Client.Update(ctx, ig)
	if err != nil {
		logger.Error(err, "update ingress on call k8s")
		return err
	}

	return nil
}

func (r *MsbDeploymentReconciler) deleteIngress(ctx context.Context, md *myAppsv1.MsbDeployment, logger logr.Logger, ig *networkv1.Ingress) error {
	err := r.Client.Delete(ctx, ig)
	if err != nil {
		logger.Error(err, "delete ingress on call k8s")
		return err
	}

	return nil
}
